package com.psbc.redislock.lock.db;

import com.psbc.redislock.domain.LockTableEasy;
import com.psbc.redislock.mapper.LockTableEasyMapper;
import com.psbc.redislock.service.LockTableEasyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Slf4j
public class EasyDBLock {
    @Autowired
    LockTableEasyService lockTableEasyService;
    @Autowired
    LockTableEasyMapper lockTableEasyMapper;

    @Transactional(rollbackFor = Exception.class)
    public boolean acquireLock(String lockName) {
        try {
            //查询锁是否存在，如果不存在，则创建锁，如果存在就说明有人占用了锁
            LockTableEasy lockTableEasy = lockTableEasyMapper.getByIdForUpdate(lockName);
//        LockTableEasy lockTableEasy = lockTableEasyService.getById(lockName);
            if (lockTableEasy == null) {
                boolean save = lockTableEasyService.save(new LockTableEasy(lockName));
                if (save) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.info("枪锁失败");
            return false;
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    public void releaseLock(String lockName) {
        //删除数据即释放了锁
        lockTableEasyService.removeById(lockName);
    }
}
